<%@ tag language="java" pageEncoding="UTF-8" trimDirectiveWhitespaces="true"%>
<%@ include file="/WEB-INF/views/utils/includes.jsp"%>
<%@ attribute name="value" type="java.lang.Object" required="true" rtexprvalue="true"%>
<%@ attribute name="idProperty" type="java.lang.String" required="true" rtexprvalue="true"%>
<%@ attribute name="nameProperty" type="java.lang.String" required="true" rtexprvalue="true"%>
<%@ attribute name="path" required="true" type="java.lang.String" rtexprvalue="false"%>
<%@ attribute name="items" type="java.lang.Object" required="true" rtexprvalue="true"%>
<%@ attribute name="required" type="java.lang.Boolean" required="false" rtexprvalue="true"%>
<%@ attribute name="enableEmpty" type="java.lang.Boolean" required="false" rtexprvalue="true"%>
<%@ attribute name="editable" required="false" type="java.lang.Boolean" rtexprvalue="true"%>
<%@ attribute name="detailUrl" required="false" type="java.lang.String" rtexprvalue="true"%>
<%@ attribute name="ajax" required="false" type="java.lang.String" rtexprvalue="true"%>
<c:choose>
	<c:when test="${editable}">
<select name="${path}" id="${path}">
	<c:if test="${enableEmpty}"><option value="">&nbsp;</option></c:if>
	<c:forEach var="item" items="${items}">
    	<option ${not empty value && item[idProperty] == value[idProperty] ? "selected" : ""} value="${item[idProperty]}"><tu:i18n value="${item[nameProperty]}"/></option>
    </c:forEach>
</select>
<script type="text/javascript">
$(document).ready (
	function () {
		var selector = "#${path.replaceAll('\\.', '\\\\\\\\.')}";
		var elem = $(selector);
<c:if test="${ajax != null}">
		var cache = new Object();
		elem.change(
	         function() {
	        	 var value = $(this).val();
	        	 if(cache[value]) {
	        		 $(selector + '-placement').html(cache[$(this).val()]);
	        		 return;
	        	 }
	        	 
	             $.get('${ajax}'.replace('%s', value)).success(
	                     function(text) {
	                    	 cache[value] = text;
	                         $(selector + '-placement').html(text);
	                     });
	         }
         );
</c:if>		
		elem.parents("form").submit(
			function(e) {
				var value = elem.val();
<c:if test="${required}">
				if(value == null || value.length == 0) {
					e.stopImmediatePropagation();
					alert('<tu:i18n value="form.validation.required"/>');
					elem.focus();
					return false;
				}
</c:if>
			}
		);
		
		elem.change();
	}
);
</script>
	</c:when>
	<c:otherwise>
		<input type="hidden" id="${path}" name="${path}" value="${value[idProperty]}">
		<gf:link url="${detailUrl}" disable="${detailUrl == null}"><tu:i18n value="${value[nameProperty]}"/></gf:link>
	</c:otherwise>
</c:choose>
